package com.hui10.mediaplayer.net

import com.hui10.mediaplayer.util.ThreadUtil
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException

/**
 * Author: Created by lucus on 2019/5/29.
 * E-mail: mcphilex1989@gmail.com
 * Tel: 15652608401
 */
class NetManager private constructor() {

    private val httpClient by lazy {
        val builder = OkHttpClient.Builder()
        builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        builder.build()
    }

    companion object {
        private val manager by lazy { NetManager() }

        fun getInstance(): NetManager {
            return manager
        }
    }

    /**
     * 发送请求
     */
    fun <RESPONSE> sendRequest(req: ARequest<RESPONSE>) {
        val request = Request.Builder()
            .get()
            .url(req.url)
            .build()
        httpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                ThreadUtil.runOnMainUIThread(Runnable {
                    req.handler.onError(req.type, e.message)
                })
            }

            override fun onResponse(call: Call, response: Response) {
                val string = response.body()?.string()
                val parseResult = req.parseResult(string)
                ThreadUtil.runOnMainUIThread(Runnable {
                    req.handler.onSuccess(req.type, parseResult)
                })
            }
        })

    }


}